from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend,OrderingFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from .models import Kind,Label,Course,Chapter,Knobble,Attention
from .serializers import KindeSer,LabelSer,CourseSer,ChapterSer,KnobbleSer
from rest_framework.response import Response
from rest_framework import viewsets
from utils.sorter import paging
from mydjango import settings
from django.http import JsonResponse

# Create your views here.

# 自定义分页器
class PageNum(PageNumberPagination):

    page_size_query_param = 'page_size'



class CourseViewSet(viewsets.ModelViewSet):

    queryset = Course.objects.all()

    serializer_class = CourseSer

    # 指定过滤方法类，排序方法类，一个或多个
    filter_backends = (DjangoFilterBackend,OrderingFilter)

    # 指定排序字段
    ordering_fields = ('guanzhu')
    
    # 指定过滤字段
    filter_fields = ('title','describe','kind','label')

    # 自定义分页器
    pagination_class = PageNum


# 返回课程类别
class CategoryView(APIView):
    def get(self,request):

        kind = Kind.objects.all().order_by('sequence')

        kindser = KindeSer(kind,many=True)

        return Response(kindser.data)

# 返回所有标签
class LabelView(APIView):
    def get(self,request):

        label = Label.objects.all().order_by('sequence')

        labelser = LabelSer(label,many=True)

        return Response(labelser.data)


# 接收前端分类参数，返回相应数据接口
class Query_Classified_Data(APIView):

    def get(self,request):

        # 接收分类
        category = request.GET.get('category','')
        # 接收当前页
        page = int(request.GET.get('page','1'))
        # 接收一页分的页数
        size = int(request.GET.get('size','3'))

        sorter = paging(page,size)

        if category == '':

            course = Course.objects.all()[sorter[0]:sorter[-1]]

            courseser = CourseSer(course,many=True)

            # 查询所有商品个数
            count = Course.objects.count()

            return Response({'code':200,'msg':'ok','data':courseser.data,'total':count})


        # 查询到分类id
        kind = Kind.objects.filter(title=category).first()

        # 关联查询
        course = Course.objects.filter(kind_id=kind.id)[sorter[0]:sorter[-1]]

        courseser = CourseSer(course,many=True)

        count = Course.objects.filter(kind_id=kind.id).count()

        return Response({'code':200,'msg':'ok','data':courseser.data,'total':count})


# 接收标签标识，查询对应数据
class Query_Label_Data(APIView):

    def get(self,request):

        # 接收标签标识
        label_marking = request.GET.get('label')

        # # 接收分类
        # category = request.GET.get('category','')

        # 接收当前页
        page = int(request.GET.get('page','1'))

        # 接收一页分的页数
        size = int(request.GET.get('size','3'))

        sorter = paging(page,size)

        # 查询标签id
        label = Label.objects.filter(title=label_marking).first()

        # 关联查询
        course = Course.objects.filter(label_id=label.id)[sorter[0]:sorter[-1]]

        # 查询总个数
        count = Course.objects.filter(label_id=label.id).count()

        courseser = CourseSer(course,many=True)

        return Response({'code':200,'msg':'ok','data':courseser.data,'total':count})



# 接收课程id查找关联章节
class Query_Chapter_Data(APIView):

    def get(self,request):

        # 接收课程id
        c_id = request.GET.get('c_id')

        # 关联查询课程下所有章节
        chapter = Chapter.objects.filter(course_id=c_id)

        chapterser = ChapterSer(chapter,many=True)


        return Response({'code':200,'msg':'ok','data':chapterser.data})

# 接收章节id查找关联节点
class Query_Knobble_Data(APIView):

    def get(self,request):

        # 接收章节id
        k_id = request.GET.get('chapter_id')

        # 关联查询章节下所有小结
        knobbles = Knobble.objects.filter(chapter_id=k_id).values_list('id','title','serial_num','learn_time')

        # knobbleser = KnobbleSer(knobble,many=True)

        return Response({'code':200,'msg':'ok','data':list(knobbles)})

# 接收课程id返回对应数据
class CourseView(APIView):
    def get(self,request):
        c_id = request.GET.get('c_id')
        print(c_id)
        # 查询数据
        course = Course.objects.filter(id=c_id)

        # 序列化
        courseser = CourseSer(course,many=True)

        return Response({'code':200,'data':courseser.data})

        

# 用户关注操作
class AttentionView(APIView):

    def post(self,request):

        # 接收相关参数
        status = request.data.get('status')

        u_id = request.data.get('u_id')

        c_id = request.data.get('c_id')

        # 判断用户是否以关注过，防止重复入库

        attention = Attention.objects.filter(user_id=u_id,course_id=c_id).first()
        
        if not attention:

            Attention(user_id=u_id,course_id=c_id).save()
        
        try:
        
            course = Course.objects.filter(id=c_id).first()

            # 用户点击关注
            if status == 1:

                course.guanzhu += 1
                # 保存到课程表
                course.save()
                return Response({'code':200,'msg':'关注成功','status':1})

            # 否则就是用户取消关注
            course.guanzhu -= 1
            # 删除关注关联表数据
            attention.delete()
            # 保存到课程表
            course.save()

            return Response({'code':200,'msg':'取消关注成功','status':0})
        except Exception as e:

            print(e)
            return Response({'code':403,'msg':'请勿频繁操作'})

    # 判断用户关注状态
    def get(self,request):
        # 接收相关参数
        u_id = request.GET.get('u_id')

        c_id = request.GET.get('c_id')

        attention = Attention.objects.filter(user_id=u_id,course=c_id).first()

        # 查到数据就是已关注
        if attention:

            return Response({'code':200,'msg':'已关注','status':1})

        else:

            return Response({'code':200,'msg':'未关注','status':0})



from django.core.paginator import InvalidPage, Paginator
from haystack.forms import ModelSearchForm

RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)


def course_index_search(request):
    query = request.GET.get('q', None)
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))
    if query:
        form = ModelSearchForm(request.GET, load_all=True)
        if form.is_valid():
            results = form.search()
        else:
            results = []
    else:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    paginator = Paginator(results, page_size)
    try:
        page = paginator.page(page)
    except InvalidPage:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    jsondata = []
    for result in page.object_list:
        data = {
            'id': result.object.id,
            'title': result.object.title,
            'desc': result.object.describe,
            'img': result.object.img,
            'follower': result.object.guanzhu,
            'status': result.object.status,
            'kind': result.object.kind.id
        }
        jsondata.append(data)
    result = {
        "code": 200,
        "msg": 'Search successfully！',
        "data": {"count": page.paginator.count, "results": jsondata}
    }
    return JsonResponse(result)
            
            
        








